package com.gframework.util;

/**
 * 网络相关操作静态工具类.<br>
 * <ul>
 * <li><strong>ipv4ToInt/intToIpv4 {@code -} </strong>ipv4和int互相转换</li>
 * </ul>
 * 
 * FIXME 未能正确的区分ipv4和ipv6，且不能转换ipv6
 * 
 * @since 1.0.0
 * @author Ghwolf
 *
 */
public final class NetUtils {
	/**
	 * 将ip地址转换为int值.<br>
	 * @param ip 要转换的ip地址
	 * @return 返回转换后的值
	 * @throws IllegalArgumentException 参数不是一个ipv4地址
	 * @throws NullPointerException 如果参数为null
	 */
	public static int ipv4ToInt(String ip) {
		int ipInt = 0 ;
		String[] arr = ip.split("\\.");
		if (arr.length != 4) {
			throw new IllegalArgumentException(ip + " 不是一个有效的ipv4地址！");
		}
		int a = 24 ;
		try {
			for (int x = 0 ; x < arr.length ; x ++) {
				ipInt += Integer.parseInt(arr[x]) << a ;
				a -= 8 ;
			}
		} catch(NumberFormatException e) {
			throw new IllegalArgumentException(ip + " 不是一个有效的ipv4地址！");
		}
		return ipInt ;
	}
	
	/**
	 * 将ip地址转换为int值.<br>
	 * @param ip 要转换的ip地址
	 * @return 返回转换后的值
	 */
	public static String intToIpv4(int ip) {
		StringBuilder sb = new StringBuilder();
		sb.append(ip >>> 24).append('.');
		sb.append((ip & 0x00FF0000) >>> 16).append('.');
		sb.append((ip & 0x0000FF00) >>> 8).append('.');
		sb.append(ip & 0x000000FF);
		return sb.toString() ;
	}
	
	public static void main(String[] args) {
//		int ip = ipv4ToInt("192.168.1.1");
//		System.out.println(ip);
//		System.out.println(intToIp(ip));
//		PerformanceAnalysis.run(NetUtils :: ipv4ToInt,"192.168.1.1");
//		PerformanceAnalysis.run(NetTools :: intToIp,-1062731519);
	}
}
